﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using DBControl;

namespace SellerProject
{
    public partial class sellDetail : TopBasePage
    {
        private string pid = "";

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString["pid"] == null)
            {
                Response.Redirect("/404.htm", false);
            }
            else
            {
                pid = Request.QueryString["pid"];

                if (!IsPostBack)
                {
                    BindSource(pid);
                    if (Session["usNick"] != null)
                    {
                        getTotalCount(pid);
                        BindSeller(pid);
                    }
                }
            }
        }

        private bool isJoin(string pid)
        {
            SqlDbHelper sdh = new SqlDbHelper();
            string getjoin = "SELECT ReleaseName from BuyersinfoR WHERE CHARINDEX(','+'" + Session["usNick"] + "'+',',','+Responder+',') > 0 AND Id='" + pid + "'";

            if (sdh.ExecuteScalar(getjoin) == null)
            {
                return false;
            }
            else
            {
                string releasename = sdh.ExecuteScalar(getjoin).ToString();
                if (releasename.Equals(Session["usNick"]))
                {
                    return true;
                }
                else if (!releasename.Equals(""))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }

        /// <summary>
        /// 查询购买需求详细数据
        /// </summary>
        /// <param name="pid">购买需求ID</param>
        private void BindSource(string pid)
        {
            SqlDbHelper sdh = new SqlDbHelper();
            string getdetail;
            if (pid == null)
            {
                getdetail = "SELECT * FROM BuyersinfoR WHERE id=null";
            }
            else
            {
                getdetail = "SELECT * FROM BuyersinfoR WHERE id='" + pid + "'";
            }
            this.myDetails.DataSource = sdh.ExecuteDataTable(getdetail);
            this.myDetails.DataBind();

            if (this.myDetails.Items.Count == 0)
            {
                this.Sellpanel.Visible = false;
            }
        }

        private void BindSeller(string pid)
        {
            if (ViewState["sortstring"] == null)
            {
                ViewState["sortstring"] = "Price";
                ViewState["sortint"] = "0";
            }

            SqlDbHelper sdh = new SqlDbHelper();
            string sqlwhere = " WHERE BuyerId='" + pid + "'";
            SqlParameter p1 = new SqlParameter("@tablename", "Sellerinfomation");//视图名或表名
            SqlParameter p2 = new SqlParameter("@pagerow", this.AspNetPager.PageSize);         //每页显示记录数 
            SqlParameter p3 = new SqlParameter("@pagenow", this.AspNetPager.CurrentPageIndex); //当前显示第几页 
            SqlParameter p4 = new SqlParameter("@ordercol", ViewState["sortstring"]);//排序字段
            SqlParameter p5 = new SqlParameter("@order", ViewState["sortint"]);//排序顺序，0升序，1降序
            SqlParameter p6 = new SqlParameter("@where", sqlwhere);
            SqlParameter[] paras = new SqlParameter[] { p1, p2, p3, p4, p5, p6 };
            this.SellView.DataSource = sdh.ExecuteDataTable("sp_page", System.Data.CommandType.StoredProcedure, null, paras);
            this.SellView.DataBind();
            if (this.SellView.Rows.Count != 0)
            {
                this.sortPanel.Visible = true;
            }
        }

        private void getTotalCount(string cid)
        {
            SqlDbHelper sdh = new SqlDbHelper();
            string sqlcount = "SELECT COUNT(*) FROM SellerinfoR WHERE BuyerId = '" + cid + "'";
            this.AspNetPager.RecordCount = int.Parse(sdh.ExecuteScalar(sqlcount).ToString());
            if (this.AspNetPager.RecordCount == 0)
            {
                this.AspNetPager.Visible = false;
            }
        }
        protected void AspNetPager_PageChanged(object sender, EventArgs e)
        {
            BindSeller(pid);
            ScriptManager.RegisterStartupScript(AspNetPager, this.GetType(), "documnetonload", "<script>documnetonload()</script>", false);
            ScriptManager.RegisterStartupScript(AspNetPager, this.GetType(), "resizeimg", "<script>ResizeImg();</script>", false);
        }
        protected void priceasc_Click(object sender, EventArgs e)
        {
            ViewState["sortstring"] = "Price";
            ViewState["sortint"] = 0;
            this.sortspan.Text = "价格由低到高";
            BindSeller(pid);
            ScriptManager.RegisterStartupScript(priceasc, this.GetType(), "documnetonload", "<script>documnetonload()</script>", false);
            ScriptManager.RegisterStartupScript(priceasc, this.GetType(), "resizeimg", "<script>ResizeImg();</script>", false);
        }

        protected void pricedesc_Click(object sender, EventArgs e)
        {
            ViewState["sortstring"] = "Price";
            ViewState["sortint"] = 1;
            this.sortspan.Text = "价格由高到低";
            BindSeller(pid);
            ScriptManager.RegisterStartupScript(pricedesc, this.GetType(), "documnetonload", "<script>documnetonload()</script>", false);
            ScriptManager.RegisterStartupScript(pricedesc, this.GetType(), "resizeimg", "<script>ResizeImg();</script>", false);
        }

        protected void honordesc_Click(object sender, EventArgs e)
        {
            ViewState["sortstring"] = "Honor";
            ViewState["sortint"] = 1;
            this.sortspan.Text = "卖家信誉由高到低";
            BindSeller(pid);
            ScriptManager.RegisterStartupScript(honordesc, this.GetType(), "documnetonload", "<script>documnetonload()</script>", false);
            ScriptManager.RegisterStartupScript(honordesc, this.GetType(), "resizeimg", "<script>ResizeImg();</script>", false);
        }

        protected void countdesc_Click(object sender, EventArgs e)
        {
            ViewState["sortstring"] = "[count]";
            ViewState["sortint"] = 1;
            this.sortspan.Text = "浏览次数由高到低";
            BindSeller(pid);
            ScriptManager.RegisterStartupScript(countdesc, this.GetType(), "documnetonload", "<script>documnetonload()</script>", false);
            ScriptManager.RegisterStartupScript(countdesc, this.GetType(), "resizeimg", "<script>ResizeImg();</script>", false);
        }

        protected void myDetails_ItemCommand(object sender, ListViewCommandEventArgs e)
        {
            ScriptManager.RegisterStartupScript(myDetails, this.GetType(), "documnetonload", "<script>documnetonload()</script>", false);
            ScriptManager.RegisterStartupScript(myDetails, this.GetType(), "resizeimg", "<script>ResizeImg()</script>", false);
            if (e.CommandName == "addbuy")
            {
                if (Session["usNick"] == null)
                {
                    ScriptManager.RegisterStartupScript(myDetails, this.GetType(), "addbuy", "<script>userLogin()</script>", false);
                }
                else
                {
                    HiddenField title = e.Item.FindControl("title") as HiddenField;
                    string buyname = Session["usNick"].ToString();
                    string buyid = e.CommandArgument.ToString();
                    string selectsql = "SELECT Id FROM BuyersinfoR WHERE CHARINDEX(','+'" + buyname + "'+',',',' + Responder + ',') > 0 AND Id='" + buyid + "'";
                    string updatesql = "UPDATE BuyersinfoR SET Responder = Responder + '," + buyname + "',Respondcount = Respondcount + 1 WHERE Id='" + buyid + "';INSERT INTO ADDaction([name],[action],[message],[actionid]) VALUES('" + Session["usNick"] + "','加入','" + title.Value + "','" + buyid + "')";
                    SqlDbHelper sdh = new SqlDbHelper();
                    try
                    {
                        if (sdh.ExecuteScalar(selectsql) == null)
                        {
                            sdh.ExecuteNonQuery(updatesql);
                            ScriptManager.RegisterStartupScript(myDetails, this.GetType(), "addok", "<script>$.success('成功加入购买，在下面的卖家信息中可以查看卖家提供的商品!', '操作成功', function (action) {if (action == 'ok') {window.location.reload();}});</script>", false);
                        }
                        else
                        {
                            ScriptManager.RegisterStartupScript(myDetails, this.GetType(), "addalready", "<script>$.success('你已经加入了购买，在下面的卖家信息中可以查看卖家提供的商品!', '操作成功');</script>", false);
                        }
                    }
                    catch (Exception)
                    {

                    }
                }
            }
        }

        protected void myDetails_ItemDataBound(object sender, ListViewItemEventArgs e)
        {
            HiddenField rename = e.Item.FindControl("ReleaseName") as HiddenField;
            HiddenField status = e.Item.FindControl("Status") as HiddenField;
            if (status.Value.Equals("1"))
            {
                e.Item.FindControl("addbuy").Visible = false;
                if (this.SellView.Rows.Count == 0)
                {
                    this.AspNetPager.Visible = true;
                    getTotalCount(Request.QueryString["pid"]);
                    BindSeller(Request.QueryString["pid"]);
                }
            }
        }

        protected void SellView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow && e.Row.RowType != DataControlRowType.EmptyDataRow)
            {
                if ((e.Row.FindControl("rname") as HiddenField).Value != Session["usNick"].ToString())
                {
                    (e.Row.FindControl("price") as Label).Text = "$$$";
                }
                else 
                {
                    ListView sv = (sender as GridView).Page.FindControl("myDetails") as ListView;
                    foreach (ListViewDataItem i in sv.Items)
                    {
                        if (i.ItemType == ListViewItemType.DataItem) { (i.FindControl("releasebtn") as Panel).CssClass = "hidden"; }
                    }
                }
            }
        }
    }
}